﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

using LibSnesDotNet.Input;

namespace LibSnesDotNet.UI
{
	class ReportInputDialog : Form
	{
		InputAggregator _aggregator;
		Predicate<InputReceivedEventArgs> _predicate;
		Label _message_lbl;
		InputID _inputID;

		public ReportInputDialog()
		{
			FormBorderStyle = FormBorderStyle.FixedToolWindow;
			ShowInTaskbar = false;

			ClientSize = new Size(300, 185);

			_message_lbl = new Label();
			_message_lbl.Width = ClientSize.Width;
			_message_lbl.TextAlign = ContentAlignment.TopCenter;
			Controls.Add(_message_lbl);
		}

		public Predicate<InputReceivedEventArgs> Predicate { get { return _predicate; } set { _predicate = value; } }
		public string Message
		{
			get { return _message_lbl.Text; }
			set
			{
				int newHeight = TextRenderer.MeasureText(value, Font, new Size(ClientSize.Width, int.MaxValue), TextFormatFlags.WordBreak).Height;

				_message_lbl.Top = (ClientSize.Height - newHeight) / 2;
				_message_lbl.Height = newHeight;
				_message_lbl.Text = value;
			}
		}
		public InputID InputID { get { return _inputID; } }


		protected override void OnLoad(EventArgs e)
		{
			Rectangle screenRect = Screen.GetWorkingArea(this);
			Left = screenRect.Left + (screenRect.Width - Width) / 2;
			Top = screenRect.Top + (screenRect.Height - Height) / 2;

			DialogResult = DialogResult.None;

			_aggregator = new InputAggregator();
			_aggregator.AddDriver(new RawInputDriver(this));

			_aggregator.ReportNextInput(_predicate, (i) =>
			{
				_inputID = i.ID;
				DialogResult = DialogResult.OK;
				Close();
			});

			base.OnLoad(e);
		}

		protected override void OnClosed(EventArgs e)
		{
			_aggregator.DisposeAllDrivers();

			if (DialogResult != DialogResult.OK) { DialogResult = DialogResult.Cancel; }

			base.OnClosed(e);
		}
	}
}
